import type React from 'react';
import { List, Button, Typography, Input } from 'antd';
import { ReloadOutlined, PlusOutlined } from '@ant-design/icons';
import { useMediaQuery } from 'react-responsive';
import InfiniteScroll from "./InfiniteScroll.tsx";

const { Title } = Typography;
const { Search } = Input;

interface ManagementProps<T> {
  title?: string;
  items: T[];
  loading: boolean;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
  hasMore: boolean;
  onSearch: (value: string) => void;
  onRefresh: () => void;
  onAdd?: () => void;
  onPageChange: (page: number, pageSize?: number) => void;
  loadMore: () => void;
  renderItem: (item: T) => React.ReactNode;
  searchPlaceholder?: string;
  addButtonText?: string;
  extraButtons?: React.ReactNode;
  renderExtraButtons?: () => React.ReactNode;
}

function Management<T>({
  title,
  items,
  loading,
  pagination,
  hasMore,
  onSearch,
  onRefresh,
  onAdd,
  onPageChange,
  loadMore,
  renderItem,
  searchPlaceholder = "搜索",
  addButtonText = "添加",
  extraButtons,
  renderExtraButtons
}: ManagementProps<T>) {
  const isMobile = useMediaQuery({ maxWidth: 767 });

  return (
    <div className="p-4">
      {title && <Title level={2}>{title}</Title>}
      <div className={`mb-4 ${isMobile ? 'flex flex-col' : 'flex justify-between items-center'}`}>
        <div className={`${isMobile ? 'mb-2 flex justify-between items-center' : 'flex'}`}>
          <Search
            placeholder={searchPlaceholder}
            onSearch={onSearch}
            className={isMobile ? 'w-3/5' : 'w-48 mr-2'}
            allowClear
          />
          <div>
            <Button icon={<ReloadOutlined />} onClick={onRefresh} style={{ marginRight: 8 }} />
            {onAdd && (
              <Button type="primary" icon={<PlusOutlined />} onClick={onAdd}>
                {addButtonText}
              </Button>
            )}
          </div>
        </div>
        {isMobile && renderExtraButtons && renderExtraButtons()}
        {!isMobile && extraButtons}
      </div>
      {isMobile ? (
        <InfiniteScroll
          loadMore={loadMore}
          hasMore={hasMore}
          isLoading={loading}
          currentPage={pagination.current}
          totalItems={pagination.total}
        >
          <List
            grid={{ gutter: 16, column: 1 }}
            dataSource={items}
            renderItem={renderItem}
          />
        </InfiniteScroll>
      ) : (
        <List
          grid={{ gutter: 16, column: 3 }}
          dataSource={items}
          renderItem={renderItem}
          pagination={{
            ...pagination,
            onChange: onPageChange,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 项`,
          }}
          loading={loading}
        />
      )}
    </div>
  );
}

export default Management;
